﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Maps.Controls;
using YellowMap.View.Control;
using System.Device.Location;

namespace YellowMap
{
    public partial class DirectionMapPage : PhoneApplicationPage
    {
        GoogleDirectionResponse DirectionResponse;
        MapPolyline polylineDirection = new MapPolyline();
        MapPolyline polylineHighlightDirection = new MapPolyline();
        MapLayer layerPushPin = new MapLayer();

        string str_minimize;
        string str_directionlist;

        List<WhiteNodePin> whiteNodePins = new List<WhiteNodePin>();

        double layoutRoot_Height, directionPanel_Height;
        public DirectionMapPage()
        {
            InitializeComponent();
            polylineDirection.StrokeColor = Constant.MAP_POLYLINE_COLOR;
            polylineDirection.StrokeThickness = Constant.MAP_POLYLINE_THICNESS;

            bingMap.MapElements.Add(polylineDirection);
            bingMap.MapElements.Add(polylineHighlightDirection);

            bingMap.Layers.Add(layerPushPin);
            ChangeMapType(AppViewModel.Instance.SettingVM.MapType);

            str_directionlist = "direction list";
            str_minimize = "minimize";
            IsShowDList = true;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
           
           DirectionResponse = MainPage.Instance.DirectionResponse;
           List<LocationPoint> locationPoints = new List<LocationPoint>();
           int count = 0;
           foreach (var s in DirectionResponse.Routes[0].Legs[0].Steps)
           {
               var llp = s.Polyline.Points;
                locationPoints.AddRange(s.Polyline.Points);
               WhiteNodePin wpin = new WhiteNodePin();
               wpin.Data.Lattitude = s.StartLocation.Lattitude;
               wpin.Data.Longitude = s.StartLocation.Longtitude;
               wpin.Data.Number = ++count;
               wpin.UpdateUI();

               //if (count < DirectionResponse.Routes[0].Legs[0].Steps.Count)
               //{
                   AddWhiteNodePin(wpin);
                   
             //  }

               DirectionListItem listItem = new DirectionListItem();
               listItem.Points = llp;
               listItem.BingMap = bingMap;
               listItem.ListBox = listDirection;
               listItem.Init(s.Distance.Text, s.HtmlInstructions, wpin);
               listDirection.Items.Add(listItem);

               if (count == DirectionResponse.Routes[0].Legs[0].Steps.Count )
               {
                    WhiteNodePin dwpin = new WhiteNodePin();
                    dwpin.Data.Lattitude = s.EndLocation.Lattitude;
                    dwpin.Data.Longitude = s.EndLocation.Longtitude;
                    dwpin.Data.Number = ++count;
                    dwpin.UpdateUI();
                    AddWhiteNodePin(dwpin);


                    DirectionListItem dlistItem = new DirectionListItem();
                    //dlistItem.Points = llp;
                    dlistItem.ListBox = listDirection;
                    dlistItem.BingMap = bingMap;
                    dlistItem.Init("", DirectionResponse.Routes[0].Legs[0].EndAddress, dwpin);
                    listDirection.Items.Add(dlistItem);
               }
           }

           foreach (var lp in locationPoints)
           {
               polylineDirection.Path.Add(new GeoCoordinate(lp.Latitude, lp.Longtitude));
           }


           if (listDirection.Items.Count > 0)
           {
               listDirection.SelectedIndex = 0;
           }

           base.OnNavigatedTo(e);

        }

        public void ClearPushPin()
        {
            layerPushPin.Clear();
        }

        public void AddWhiteNodePin(WhiteNodePin pin)
        {
            // pin.OnShowDetail += pin_OnShowDetail;
            MapOverlay overlay = new MapOverlay();
            overlay.GeoCoordinate = new GeoCoordinate(pin.Data.Lattitude, pin.Data.Longitude);
            overlay.Content = pin;
            layerPushPin.Add(overlay);
        }

        #region StateManager
        public void ShowDirectionList()
        {
            VisualStateManager.GoToState(this, "show", true);
        }

        public void HideDirectionList()
        {
            VisualStateManager.GoToState(this, "hide", true);
        } 
        #endregion

        #region ChangeMapType
        public void ChangeMapType(int type)
        {
            switch (type)
            {
                case 0:
                    bingMap.CartographicMode = MapCartographicMode.Road;
                    break;
                case 1:
                    bingMap.CartographicMode = MapCartographicMode.Aerial;
                    break;
                case 2:
                    bingMap.CartographicMode = MapCartographicMode.Hybrid;
                    break;
                case 3:
                    bingMap.CartographicMode = MapCartographicMode.Terrain;
                    break;
                default:
                    break;
            }
        } 
        #endregion


        #region MyRegion
        private void directionPanel_SizeChanged(object sender, System.Windows.SizeChangedEventArgs e)
        {
            // TODO: Add event handler implementation here.
            directionPanel_Height = e.NewSize.Height;
            bingMap.Height = layoutRoot_Height - directionPanel_Height;
        }

        private void LayoutRoot_SizeChanged(object sender, System.Windows.SizeChangedEventArgs e)
        {
            // TODO: Add event handler implementation here.
            layoutRoot_Height = e.NewSize.Height;
            bingMap.Height = layoutRoot_Height - directionPanel_Height;
        }

         
        #endregion

        bool _iShowDList;
        public bool IsShowDList
        {
            get {
                return _iShowDList;
            }
            set {
                _iShowDList = value;
                if (value)
                {
                    //listDirection.Visibility = System.Windows.Visibility.Visible;
                    VisualStateManager.GoToState(this, "showlist", true);
                    btnMinimize.Content = str_minimize;
                }
                else
                {
                    //listDirection.Visibility = System.Windows.Visibility.Collapsed;
                    VisualStateManager.GoToState(this, "hidelist", true);
                    btnMinimize.Content = str_directionlist;
                }
            }
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            
            if (IsShowDList==true)
            {
                IsShowDList = false;
                e.Cancel = true;
                return;
            }
            base.OnBackKeyPress(e);
        }


        private void btnMinimize_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            IsShowDList = !IsShowDList;
        }

        private void listDirection_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
        	// TODO: Add event handler implementation here.
            (listDirection.SelectedItem as DirectionListItem).IsSelected = true;
        }

        private void btnGoNext_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	// TODO: Add event handler implementation here.

            int selectedIndex = listDirection.SelectedIndex;
            if (selectedIndex == listDirection.Items.Count - 1)
            {
                (listDirection.SelectedItem as DirectionListItem).IsSelected = true;
            }
            else
            {
                listDirection.SelectedIndex++;
            }

        }

        private void btnGoBack_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            int selectedIndex = listDirection.SelectedIndex;
            if (selectedIndex == 0)
            {
                (listDirection.SelectedItem as DirectionListItem).IsSelected = true;
            }
            else
            {
                listDirection.SelectedIndex--;
            }
        }
    }
}